import routeSettings from "@/config/route"
import { setRouteChange } from "@/hooks/useRouteListener"
import { useTitle } from "@/hooks/useTitle"
import router from "@/router"
import { usePermissionStoreHook } from "@/store/modules/permission"
import { useUserStore } from "@/store/modules/user"
import { getToken } from "@/utils/cache/cookies"
import { fixBlankPage } from "@/utils/fix-blank-page"
import NProgress from "nprogress"
import "nprogress/nprogress.css"

const { setTitle } = useTitle()
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, _from, next) => {
  fixBlankPage()
  NProgress.start()
  const userStore = useUserStore()
  const permissionStore = usePermissionStoreHook()
  userStore.setRoles(routeSettings.defaultRoles)
  permissionStore.setRoutes(routeSettings.defaultRoles)

  if (to.path === "/login" && getToken()) {
    // 如果当前路径是"/login"且用户已登录，则导航到主页
    router.push("/")
  } else if (to.path !== "/login" && !getToken()) {
    // 如果当前路径不是"/login"且用户未登录，则重定向到登录页面
    next("/login")
  } else {
    // 其他情况，继续执行路由守卫的下一个步骤
    next()
  }
})

router.afterEach((to) => {
  setRouteChange(to)
  setTitle(to.meta.title)
  NProgress.done()
})
